package servidor.principal.control;

import comun.dto.*;

import comun.iControl.*;


import java.rmi.server.UnicastRemoteObject;
import java.util.*; 

import servidor.principal.assembler.*;
import servidor.dominio.Cliente;
import servidor.dominio.Comprobante; 
import servidor.dominio.LibroIva;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Extent;
import javax.jdo.Query;
import javax.jdo.JDOHelper;
import javax.jdo.Transaction;
import servidor.dominio.*; 


public class ControlComprobante extends UnicastRemoteObject implements IControlComprobante{


    public ControlComprobante() throws Exception{   }

    public void delComprobanteDTO(String nroComprobante) throws Exception {
    	PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
    	PersistenceManager pm = pmf.getPersistenceManager();
    	Transaction tx=pm.currentTransaction();
    	try{
    		if (!tx.isActive())tx.begin();
    		Comprobante p = new Comprobante();
    		String filter = "nroComprobante == \""+nroComprobante+"\"";
    		Collection<Comprobante> comprobanteCol= this.getObjects(pm,Comprobante.class,filter);
    		Iterator<Comprobante> iter = comprobanteCol.iterator();
    		while (iter.hasNext()) {
    			Comprobante comprobante = iter.next();
    			ComprobanteDTO comprobanteDTO = ComprobanteAssembler.getComprobanteDTO(comprobante);
    			pm.deletePersistent(comprobante);	 
    		}
    		tx.commit();
    		System.out.println("Comprobante dado de baja. OK");
    	}
    	finally {
    		if (tx.isActive())
    		{
    			tx.rollback();
    		}
    		pm.close();
    	} 

    }

    public boolean addComprobanteDTO(ComprobanteDTO comprobanteDTO,LibroIvaDTO libIvaDTO) throws Exception {
    	PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx=pm.currentTransaction();
        try{ 
        	tx.begin();
        	System.out.println("estoy por agregar un comprobante");
        
 	       	
	        ComprobanteAssembler comprobanteAssembler = new ComprobanteAssembler();
	        String filter = "id == \""+libIvaDTO.getId()+"\"";
		    LibroIva libroIva = (LibroIva) this.getObjects(pm,LibroIva.class,filter);
 	        Comprobante comprobante= ComprobanteAssembler.getComprobante(comprobanteDTO);
 	        comprobante.setLibroIva(libroIva);
		    comprobanteDTO=ComprobanteAssembler.getComprobanteDTO(comprobante);    			 
		    pm.makePersistent(comprobante);
		    tx.commit();
		    System.out.println("Comprobante dado de alta. OK"); 	
    			
    		}
    		finally
            {
                if (tx.isActive())
                {
                    tx.rollback();
                }
                pm.close();
            }                
    	return true;
    	}

    public boolean addComprobanteDTO(ComprobanteDTO comprobanteDTO,String cuitCliente, String mes, String anio) throws Exception {
    	PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
        PersistenceManager pm = pmf.getPersistenceManager();
        Transaction tx=pm.currentTransaction();
        try{ 
        	tx.begin();       
 	       	
	        ComprobanteAssembler comprobanteAssembler = new ComprobanteAssembler();
	        ControlLibroIva controlLibroIva = new ControlLibroIva() ;
		    LibroIva libroIva= new LibroIva();
		    
		    String filter = "cuit ==\""+cuitCliente+"\"";
            Cliente cliente = (Cliente)this.getObject(pm, Cliente.class, filter);            
            filter = "mes ==\""+mes+"\" && anio ==\""+anio+"\"";
            Collection libIvas=  this.getObjects(pm,LibroIva.class,filter);
            Iterator it = libIvas.iterator();            
            while (it.hasNext()){
            	libroIva = (LibroIva) it.next();
            	if (libroIva.getCliente().getId()==cliente.getId()){
            		break;
            	}
            }		    
 	        
		    Comprobante comprobante= ComprobanteAssembler.getComprobante(comprobanteDTO);
 	        comprobante.setLibroIva(libroIva);
		    comprobanteDTO=ComprobanteAssembler.getComprobanteDTO(comprobante);    			 
		    pm.makePersistent(comprobante);
		    tx.commit();
		       			
    		}
    		finally
            {
                if (tx.isActive())
                {
                    tx.rollback();
                }
                pm.close();
            }                
    	return true;
    	}


    public boolean existeComprobante(String nroComprobante) throws Exception {
    	PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
    	PersistenceManager pm = pmf.getPersistenceManager();
    	Transaction tx=pm.currentTransaction();
    	tx = pm.currentTransaction();
    	boolean existe = false;
    	try {
    		if (!tx.isActive())tx.begin();
    		String filter = "fecha == \""+nroComprobante+"\"";
    		Collection comprobanteCol= this.getObjects(pm,Comprobante.class,filter);
    		if (comprobanteCol.size()==1) 
    			existe=true;
    		try {
    			tx.commit(); 
    		} catch (RuntimeException e) {
    			e.printStackTrace();
    			return false;
    		}
    	} finally {
    		if (tx.isActive()) tx.rollback();
    	}
    	return existe;
    } 
       
	

	public Vector<ComprobanteDTO> getComprobante(String nroComprobante) throws Exception {
		// TODO Auto-generated method stub
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
    	PersistenceManager pm = pmf.getPersistenceManager();
    	Transaction tx=pm.currentTransaction();
    	tx = pm.currentTransaction();
    	 Vector<ComprobanteDTO> vector = new Vector<ComprobanteDTO>();
    	Collection<Comprobante> consultaCol = null;  
		try
		{
			if (!tx.isActive())tx.begin();
            String filter = "nroComprobante == \""+nroComprobante+"\"";
            consultaCol= this.getObjects(pm,Comprobante.class,filter);
            Iterator<Comprobante> iter = consultaCol.iterator();
            while (iter.hasNext()){
		    	Comprobante comprobante = iter.next();
		    	ComprobanteDTO comprobanteDTO = ComprobanteAssembler.getComprobanteDTO(comprobante);
		    	vector.add(comprobanteDTO);
		    }

		    tx.commit();
		}
		catch (Exception e){
		    if (tx.isActive())
		    {
		        tx.rollback();
		    }
		}
		finally {
        	if (tx.isActive()) tx.rollback();
        }
		return vector;
		
	}
	public Vector<ComprobanteDTO> getComprobanteAux() throws Exception {
		// TODO Auto-generated method stub
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
    	PersistenceManager pm = pmf.getPersistenceManager();
    	Transaction tx=pm.currentTransaction();
	
	    tx = pm.currentTransaction();
	    Collection<Comprobante> consultaCol = null;       
	    Vector<ComprobanteDTO> vector = new Vector<ComprobanteDTO>();
	    
	        try {
	            if (!tx.isActive())tx.begin();
	            consultaCol= this.getObjects(pm,Comprobante.class,null);
	            Iterator<Comprobante> iter = consultaCol.iterator();
	            while (iter.hasNext()) {
	            	Comprobante p = iter.next();
	            	ComprobanteDTO pDTO =ComprobanteAssembler.getComprobanteDTO(p);
	            	vector.add(pDTO);
	            	
	            }            
	            tx.commit();
	        } catch (RuntimeException e) {
	        	e.printStackTrace();
	        } finally {
	        	if (tx.isActive()) tx.rollback();
	        }
	        return vector;
	 
	}

	
	public Collection getObjects(PersistenceManager pm, Class clase,String filter)throws Exception{
     	Collection retorno=null;
     	try{
             Class clienteClass = clase;
             Extent clnCliente = pm.getExtent(clienteClass, false);
             Query query = pm.newQuery(clnCliente,filter);
             retorno=(Collection)query.execute();
     	} catch(Exception e) {
             throw e;
     	}
     	return retorno;
     }
    
    public Object getObject(PersistenceManager pm,Class clase,String filter) throws Exception{
    	Object objetoPersistente = null;
        try {
	        
        	Extent clnObject = pm.getExtent(clase, true);
	        Query query = pm.newQuery(clnObject,filter);
	        Collection objetos = (Collection)query.execute();
	        
	        
	        Object[] prueba = objetos.toArray();
	        if(prueba.length > 0){
	            	objetoPersistente = prueba[0];
	        }	
	    }
        catch (Exception ex) {
        	ex.printStackTrace();
            throw ex;           
        }
        return objetoPersistente;
    }
   
    public Vector<ComprobanteDTO> getComprobante(LibroIvaDTO libroIva) throws Exception {
		// TODO Auto-generated method stub
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
    	PersistenceManager pm = pmf.getPersistenceManager();
    	Transaction tx=pm.currentTransaction();
    	tx = pm.currentTransaction();
    	Vector<ComprobanteDTO> vector = new Vector<ComprobanteDTO>();
    	Collection<Comprobante> consultaCol = null;  
    	ComprobanteDTO comprobanteDTO = new ComprobanteDTO();
    	 try {
			if (!tx.isActive())tx.begin();
            consultaCol= this.getObjects(pm,Comprobante.class,"");
            Iterator<Comprobante> iter = consultaCol.iterator();
            System.out.println("hay "+ consultaCol.size() +"comprobantes");
           
            while (iter.hasNext()){
		    	Comprobante comprobante = iter.next();
		    	if (comprobante.getLibroIva().getId()==(libroIva.getId())){
		    		comprobanteDTO = ComprobanteAssembler.getComprobanteDTO(comprobante);	
		    		vector.add(comprobanteDTO);		    	
		    	}
		    }
            tx.commit();
	        } catch (RuntimeException e) {
	        	e.printStackTrace();
	        } finally {
	        	if (tx.isActive()) tx.rollback();
	        }
        return vector;		
	}

}

	



	

